package com.xuerhua.yxt.excel.support;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Excel（XLS)文件解析类
 *
 *
 */
public class XLSParser implements IExcelParser {
    /** LOG*/
    protected final static Logger LOG = LoggerFactory.getLogger(XLSParser.class);

    /**
     * 将输入流解析为List集合
     * @param is 流
     * @return list
     */
    public List<List<String>> parse(InputStream is){
        try {
            Workbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
            final Sheet sheet = wb.getSheetAt(0);
            List<List<String>> excelData = new ArrayList<List<String>>();

            for (int i = 0, len = sheet.getLastRowNum(); i <= len; i++) {
                Row row = sheet.getRow(i);
                int columnLen = row.getLastCellNum();
                List<String> colsData = new ArrayList<String>();
                for (int j = 0; j <= columnLen; j++) {
                    colsData.add(getCellContent(row.getCell(j)));
                }
                excelData.add(colsData);
            }
            return excelData;
        } catch (IOException e) {
            LOG.error("XLS文件解析失败", e);
            throw new ExcelParseException("XLS文件解析失败");
        }

    }

    /**
     * 获取单元格内容，返回字符串
     *
     * @param cell Cell
     * @return str
     */
    protected static String getCellContent(Cell cell) {
        String content = null;
        if (cell != null) {
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_STRING:
                    content = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    content = String.valueOf(cell.getNumericCellValue());
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    content = String.valueOf(cell.getBooleanCellValue());
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    content = cell.getCellFormula();
                    break;
                default:
                    content = null;
            }
        }
        return content;
    }
}
